package main.service.mail.http.main;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class URLConnection {
    // ip 不能填127.0.0.1
    private static String ip = "https://api.exmail.qq.com/cgi-bin/";
    public static String request(String path) {
        HttpURLConnection connection = null;
        InputStream stream = null;
        BufferedReader reader = null;
        String server = ip+path;
        try {
// 实例化URL对象
            URL url = new URL(server);
// 通过URL对象打开一个连接，显示转换为httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
// 设置连接方式：get
            connection.setRequestMethod("GET");
// 设置连接远程服务的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
// 设置读取远程服务返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
// 建立连接，发送请求
            connection.connect();
// 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
// 从打开的连接获取输入流，接收返回数据
                stream = connection.getInputStream();
// 实例化BufferedReader对象，并指定字符集
                reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
// 实例化字符串生成器
                StringBuffer sbf = new StringBuffer();
                String temp = null;
// 从输入流读取数据
                while ((temp = reader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
// 返回内容输出到控制台
                System.out.println("远程服务返回的数据：" + sbf.toString());
                return sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
// 关闭资源
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != stream) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
// 关闭远程连接
            connection.disconnect();
        }
        return null;
    }

    public static String sendPost(String url,String param){
        url = ip+url;
        OutputStreamWriter out =null;
        BufferedReader reader = null;
        String response = "";

        //创建连接
        try {
            URL httpUrl = null; //HTTP URL类 用这个类来创建连接
            //创建URL
            httpUrl = new URL(url);
            //建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setUseCaches(false);//设置不要缓存
            conn.setInstanceFollowRedirects(true);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //POST请求
            out = new OutputStreamWriter(
                    conn.getOutputStream());
            out.write(param);
            out.flush();
            //读取响应
            reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                response+=lines;
            }
            reader.close();
            // 断开连接
            conn.disconnect();

        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(reader!=null){
                    reader.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }

        System.out.println(response);
        return response;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostParam(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        url = ip+url;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            java.net.URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }


}